import { 
  TransactionRequest, 
  TransactionResponse, 
  BalanceResponse, 
  StateRootResponse,
  BlockResponse,
  BlocksResponse
} from './crypto';
import { checkServerStatus, handleNetworkError, safeJsonParse } from './server';
import { ZHAIQUAN_ROLLUP_URL } from './config';

// API 配置管理
export interface APIConfig {
  baseUrl: string;
}

export class APIError extends Error {
  constructor(message: string, public status?: number) {
    super(message);
    this.name = 'APIError';
  }
}

// API 客户端类
export class APIClient {
  private config: APIConfig;

  constructor(config: APIConfig) {
    this.config = config;
  }

  // 检查服务器是否运行
  async checkServerRunning(): Promise<boolean> {
    return checkServerStatus(`${this.config.baseUrl}/state/root`, 3000);
  }

  // 获取状态根
  async getStateRoot(): Promise<string> {
    try {
      const response = await fetch(`${this.config.baseUrl}/state/root`);
      if (!response.ok) {
        throw new APIError(`获取状态根失败: ${response.statusText}`, response.status);
      }
      
      const result: StateRootResponse = await safeJsonParse(response);
      return result.stateRoot;
    } catch (error) {
      handleNetworkError(error);
    }
  }

  // 发送交易
  async sendTransaction(txReq: TransactionRequest): Promise<TransactionResponse> {
    try {
      const response = await fetch(`${this.config.baseUrl}/transaction/send`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(txReq),
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new APIError(`发送交易失败: ${errorText}`, response.status);
      }

      return await safeJsonParse(response);
    } catch (error) {
      handleNetworkError(error);
    }
  }

  // 获取交易状态
  async getTransactionStatus(txHash: string): Promise<TransactionResponse> {
    try {
      const response = await fetch(`${this.config.baseUrl}/transaction/get?hash=${txHash}`);
      if (!response.ok) {
        throw new APIError(`获取交易状态失败: ${response.statusText}`, response.status);
      }
      
      return await safeJsonParse(response);
    } catch (error) {
      handleNetworkError(error);
    }
  }

  // 获取账户余额
  async getBalance(address: string): Promise<BalanceResponse> {
    try {
      const response = await fetch(`${this.config.baseUrl}/balance/get?address=${address}`);
      if (!response.ok) {
        throw new APIError(`获取余额失败: ${response.statusText}`, response.status);
      }
      
      return await safeJsonParse(response);
    } catch (error) {
      handleNetworkError(error);
    }
  }

  // 获取所有区块信息
  async getAllBlocks(): Promise<BlockResponse[]> {
    try {
      const response = await fetch(`${this.config.baseUrl}/blocks`);
      if (!response.ok) {
        throw new APIError(`获取区块信息失败: ${response.statusText}`, response.status);
      }
      
      const result: BlocksResponse = await safeJsonParse(response);
      if (result.status !== 'success') {
        throw new APIError(`获取区块请求失败: ${result.status}`);
      }
      
      return result.data.blocks;
    } catch (error) {
      handleNetworkError(error);
    }
  }

  // 获取账户nonce
  async getNonce(address: string): Promise<number> {
    try {
      const response = await fetch(`${this.config.baseUrl}/account/nonce?address=${address}`);
      if (!response.ok) {
        throw new APIError(`获取nonce失败: ${response.statusText}`, response.status);
      }
      
      const result = await safeJsonParse<{ nonce: number }>(response);
      return result.nonce || 0;
    } catch (error) {
      console.warn(`获取账户 ${address} nonce失败:`, error);
      return 0;
    }
  }

  // 等待交易确认
  async waitForConfirmation(
    txHash: string, 
    maxRetries: number = 10, 
    retryInterval: number = 3000
  ): Promise<boolean> {
    for (let i = 0; i < maxRetries; i++) {
      try {
        const tx = await this.getTransactionStatus(txHash);
        if (tx.status === 'confirmed') {
          return true;
        }
        
        if (i < maxRetries - 1) {
          await new Promise(resolve => setTimeout(resolve, retryInterval));
        }
      } catch (error) {
        console.warn(`检查交易状态失败 (尝试 ${i + 1}/${maxRetries}):`, error);
        if (i < maxRetries - 1) {
          await new Promise(resolve => setTimeout(resolve, retryInterval));
        }
      }
    }
    
    return false;
  }
}

// Hook: 根据当前页面路径创建 API 客户端
export function useAPIClient(): APIClient {
  return new APIClient({ 
    baseUrl: ZHAIQUAN_ROLLUP_URL,
  });
}
